package com.xiamao.jdt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MaxChargePercentRedisService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String HASH_KEY = "max_charge_percentages";
    private static final long EXPIRE_TIME = 4; // 12小时
    
    /**
     * 设置最大充电百分比
     * @param key deviceId:interfaceId
     * @param maxPercent 最大充电百分比
     */
    public void setMaxChargePercent(String key, Integer maxPercent) {
        // 如果key不存在，创建key并设置过期时间
        if (Boolean.FALSE.equals(redisTemplate.hasKey(HASH_KEY))) {
            redisTemplate.opsForHash().putAll(HASH_KEY, new HashMap<>());
            redisTemplate.expire(HASH_KEY, EXPIRE_TIME, TimeUnit.HOURS);
        }
        redisTemplate.opsForHash().put(HASH_KEY, key, maxPercent.toString());
    }

    public void unSetMaxChargePercent(String key) {
        // 如果key不存在，创建key并设置过期时间
        if (Boolean.FALSE.equals(redisTemplate.hasKey(HASH_KEY))) {
          return;
        }
        redisTemplate.opsForHash().delete(HASH_KEY, key);
    }

    public void setCarNoChargePercent(String key, Integer maxPercent) {
        // 如果key不存在，创建key并设置过期时间
        if (Boolean.FALSE.equals(redisTemplate.hasKey(HASH_KEY))) {
            redisTemplate.opsForHash().putAll(HASH_KEY, new HashMap<>());
            redisTemplate.expire(HASH_KEY, EXPIRE_TIME, TimeUnit.HOURS);
        }
        redisTemplate.opsForHash().put(HASH_KEY, key, maxPercent.toString());
    }
    
    /**
     * 获取最大充电百分比
     * @param key deviceId:interfaceId
     * @return 最大充电百分比
     */
    public Integer getMaxChargePercent(String key) {
        Object value = redisTemplate.opsForHash().get(HASH_KEY, key);
        if (value != null) {
            return Integer.valueOf(value.toString());
        }
        return null;
    }
    
    /**
     * 获取所有设置
     * @return 所有设置的映射
     */
    public Map<String, Integer> getAllMaxChargePercents() {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(HASH_KEY);
        Map<String, Integer> result = new HashMap<>();
        
        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            result.put(entry.getKey().toString(), Integer.valueOf(entry.getValue().toString()));
        }
        return result;
    }
}